package com.swak.p2p;

import java.util.Map;
import java.util.concurrent.CompletionStage;

import com.swak.Constants;
import com.swak.OS;
import com.swak.exception.RemotingException;
import com.swak.reactivex.p2p.Exchangers;
import com.swak.reactivex.p2p.exchange.ExchangePeer;
import com.swak.reactivex.transport.Channel;
import com.swak.reactivex.transport.ExchangeChannel;
import com.swak.reactivex.transport.ExchangeHandlerAdapter;
import com.swak.reactivex.transport.Message;
import com.swak.reactivex.transport.resources.LoopResources;
import com.swak.registry.URL;
import com.swak.utils.Maps;

@Deprecated
public class PeerB extends AbsPeer {

	private ExchangePeer server;

	public PeerB(LoopResources resources) throws RemotingException {
		URL group = new URL("p2p", "224.0.0.1", 60002, Maps.newHashMap());
		Map<String, String> parameters = Maps.newHashMap();
		parameters.put(Constants.Bind_Host, Constants.ANYHOST);
		parameters.put(Constants.Heartbeat, String.valueOf(Constants.Default_Heartbeat));
		URL peer = new URL("Test", OS.ip(), OS.randomAvailablePort(), parameters);
		this.server = Exchangers.join(group, peer, resources, new ExchangeHandlerAdapter() {

			@Override
			public CompletionStage<Object> reply(ExchangeChannel channel, Object message) throws RemotingException {
				return super.reply(channel, message);
			}

			@Override
			public void connected(Channel channel) throws RemotingException {
				super.connected(channel);
				System.out.println("建立连接:" + channel);
			}

			@Override
			public void disconnected(Channel channel) throws RemotingException {
				super.disconnected(channel);
			}

			@Override
			public void sent(Channel channel, Object message) throws RemotingException {
				super.sent(channel, message);
			}

			@Override
			public void received(Channel channel, Object message) throws RemotingException {
				super.received(channel, message);
				System.out.println("B 收到数据  ：" + ((Message) message).getData());
			}

			@Override
			public void caught(Channel channel, Throwable exception) throws RemotingException {
				super.caught(channel, exception);
			}
		});
	}

	public void send() throws RemotingException {
		this.server.send("发送数据");
	}
}
